package com.example.string;

import org.junit.Test;

/**
 * @author readpage
 * @create 2022-09-07 20:38
 */
public class StringDemo {
    /**
     * 将一个字符串进行反转。将字符串中指定部分进行反转。比如"abcdefg"反转为abfedcg"
     *
     * 方式一: 转为char[]
     */

    public String reverse(String str, int startIndex, int endIndex) {
        char[] arr = str.toCharArray();
        if (str == null) return null;
        for (int x = startIndex, y = endIndex; x < y; x++, y--) {
            char temp = arr[x];
            arr[x] = arr[y];
            arr[y] = temp;
        }
        return new String(arr);
    }

    // 方式二: 使用String的拼接
    public String reverse2(String str, int startIndex, int endIndex) {
        if (str == null) return null;
        //第一部分
        String reverseStr = str.substring(0, startIndex);
        //第二部分
        for (int i = endIndex; i >= startIndex; i--) {
            reverseStr += str.charAt(i);
        }
        //第三部分
        reverseStr += str.substring(endIndex+1);
        return reverseStr;
    }

    //方式三: 使用StringBuffer/StringBuilder替换String
    public String reverse3(String str, int startIndex, int endIndex) {
        if (str == null) return null;
        StringBuilder builder = new StringBuilder(str.length());

        //第一部分
        builder.append(str.substring(0, startIndex));
        //第二部分
        for (int i = endIndex; i >= startIndex; i--) {
            builder.append(str.charAt(i));
        }
        //第三部分
        builder.append(str.substring(endIndex+1));
        return builder.toString();
    }

    @Test
    public void testReverse() {
        String str = "abcdefg";
        String reverse = reverse3(str, 2, 5);
        System.out.println(reverse);
    }
}
